<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 开发环境版本，包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <style>
       table tr td {
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <div id="app">
        <h1>书城购物车</h1>
        <table style="border: 1px solid black;">
            <tr>
                <td>
                    {{goods[0].name}}
                </td>
                <td>单价 {{goods[0].price}}</td>
                <td><button @click="subtraction(0)">-</button> {{goods[0].num}}
                    <button v-on:click="add(0)">+</button>
                </td>
            </tr>
            <tr>
                <td>
                    {{goods[1].name}}
                </td>
                <td>单价 {{goods[1].price}}</td>
                <td><button @click="subtraction(1)">-</button> {{goods[1].num}}
                    <button v-on:click="add(1)">+</button>
                </td>
            </tr>
            <tr>
                <td>
                    {{goods[2].name}}
                </td>
                <td>单价 {{goods[2].price}}</td>
                <td><button @click="subtraction(2)">-</button> {{goods[2].num}}
                    <button v-on:click="add(2)">+</button>
                </td>
            </tr>
        </table>
        <br>
        总和：{{sum}}

    </div>
    <script>
        new Vue({
            //绑定到上面view页面中的dom节点，该节点内部就可以使用vue的组件
            el: "#app",
            data() {
                return {
                    goods: [
                        {   
                            name:'java最牛逼',
                            price: 99,
                            num: 0
                        },
                        {
                            name:'php是世界上最好的语言',
                            price: 19,
                            num: 0
                        },
                        {
                            name:'python谁也打不过',
                            price: 39,
                            num: 0
                        }
                    ],
                    sum: 0
                }
            },
            methods: {
                subtraction(index) {
                    if (this.goods[index].num < 1) {
                        alert("数量不能小于0")
                        return
                    }
                    this.goods[index].num -= 1
                    this.sum -= this.goods[index].price
                },
                add(index) {
                    this.goods[index].num += 1
                    this.sum += this.goods[index].price
                }
            },
        });
    </script>
</body>

</html>